package com.lee.account.controller;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.lee.account.entity.SysUser;
import com.lee.account.jwt.PassToken;
import com.lee.account.jwt.Token;
import com.lee.account.service.SysUserService;
import com.lee.account.utils.Constants;
import com.lee.account.utils.MD5;
import com.lee.account.utils.R;

/**
 * OauthController
 * @author liyou
 * @date 2019年9月3日 下午4:01:47
 */
@RestController
@RequestMapping("/token")
public class OauthController {
	
	public static final Logger logger = LoggerFactory.getLogger(OauthController.class);

	@Autowired
	private  SysUserService sysUserService;
	@PostMapping("/refresh")
	public R refresh(SysUser user) {
		try {
			Wrapper<SysUser> userCondi = new EntityWrapper<>();
			userCondi.eq("username", user.getUsername());
			
			SysUser refreshUser = sysUserService.selectOne(userCondi);
			
			String access_token = Token.getToken(refreshUser);
			return R.success().put("user", refreshUser).put("access_token", access_token).put("expiresTime", Constants.CLIENT_TOKEN_REFRESH_TIME);
		} catch (Exception e) {
			logger.error("刷新token异常：", e);
			return R.serverError();
		}
	}
	
	
	@PassToken
	@PostMapping("/oauth")
	public R oauth(SysUser user) {
		try {
			Wrapper<SysUser> userCondi = new EntityWrapper<>();
			userCondi.eq("username", user.getUsername());
			
			SysUser loginUser = sysUserService.selectOne(userCondi);
			
			if(loginUser == null ) {
				return R.error("用户名不存在!");
			}
			
			if(!MD5.verify(user.getPassword(), loginUser.getPassword())) {
				return R.error("密码不正确!");
			}
			
			String access_token = Token.getToken(loginUser);
			
			SysUser updateUser = new SysUser();
			updateUser.setId(loginUser.getId());
			updateUser.setLastLoginTime(new Date());
			updateUser.setLoginCount(loginUser.getLoginCount() + 1);
			updateUser.setLastLoginIp(user.getLastLoginIp());
			updateUser.setLastLoginAddress(user.getLastLoginAddress());
			sysUserService.updateById(updateUser);
			
			return R.success().put("user", loginUser).put("access_token", access_token).put("expiresTime", Constants.CLIENT_TOKEN_REFRESH_TIME);
		} catch (Exception e) {
			logger.error("登录异常：", e);
			return R.serverError();
		}
	}
}
